package admin

import (
	"strconv"

	adminModel "github.com/cn-joyconn/goadmin/models/admin"
	defaultOrm "github.com/cn-joyconn/goadmin/models/defaultOrm"
	global "github.com/cn-joyconn/goadmin/models/global"
	gocache "github.com/cn-joyconn/gocache"
	gologs "github.com/cn-joyconn/gologs"
	joyarray "github.com/cn-joyconn/goutils/array"
	strtool "github.com/cn-joyconn/goutils/strtool"
)

var appCacheObj *gocache.Cache

type AdminAppService struct {
}

func init() {
	appCacheObj = &gocache.Cache{
		Catalog:   global.AdminCatalog,
		CacheName: global.AdminCacheName,
	}
}

// 获取缓存用的键
// 返回值 缓存key
func (service *AdminAppService) getAppNameCacheKey(name string) string {
	return "app_name_" + name
}
func (service *AdminAppService) removeNameAppCache(name string) {
	appCacheObj.Delete(service.getAppNameCacheKey(name))
}

// 获取缓存用的键
// 返回值 缓存key
func (service *AdminAppService) getAppIDCacheKey(id int) string {
	return "app_id_" + strconv.Itoa(id)
}
func (service *AdminAppService) removeIDAppCache(id int) {
	appCacheObj.Delete(service.getAppIDCacheKey(id))
}

/**
*修改应用状态应用
* @param pId 应用id
* @param pState 状态 1正常 0禁用
* @return 结果 1:成功 小于1:失败
 */
func (service *AdminAppService) UpdateStateByPrimaryKey(pId int, pState int) int64 {
	record := &adminModel.AdminApp{}
	record.PId = pId
	record.PState = pState
	result := defaultOrm.DB.Model(&record).Select("PState").Updates(record)
	if result.Error != nil {
		gologs.GetLogger("orm").Error(result.Error.Error())
		return 0
	}
	return result.RowsAffected
}

/**
*添加应用
* @param record 应用实例
* @return 结果 1:成功 小于1:失败
 */
func (service *AdminAppService) Insert(record *adminModel.AdminApp) int {
	record.PNameMd5 = strtool.Md5(record.PName)
	result := defaultOrm.DB.Model(&record).Create(record)
	if result.Error != nil {
		gologs.GetLogger("orm").Error(result.Error.Error())
	}
	if record.PId > 0 {
		return record.PId
	} else {
		return -1
	}
}

/**
*获取整个应用
* @param pId 应用id
* @return  未找到时返回null
 */
func (service *AdminAppService) SelectAppById(pId int) (error, *adminModel.AdminApp) {
	cacheKey := service.getAppIDCacheKey(pId)
	var result *adminModel.AdminApp
	err := menuCacheObj.Get(cacheKey, &result)
	if err != nil || result == nil {
		var data adminModel.AdminApp
		err = defaultOrm.DB.Where("f_id = ?", pId).First(&data).Error
		if err == nil {
			roleCacheObj.Put(cacheKey, &data, 1000*60*60*24)
			result = &data
		}

	}
	return err, result
}

/**
*获取整个应用
* @param pId 应用id
* @return  未找到时返回null
 */
func (service *AdminAppService) SelectAppByName(name string) (error, *adminModel.AdminApp) {
	cacheKey := service.getAppNameCacheKey(name)
	var result *adminModel.AdminApp
	err := menuCacheObj.Get(cacheKey, &result)
	if err != nil || result == nil {
		var data adminModel.AdminApp
		err = defaultOrm.DB.Where("f_name_md5 = ?", strtool.Md5(name)).First(&data).Error
		if err == nil {
			roleCacheObj.Put(cacheKey, &data, 1000*60*60*24)
			result = &data
		}

	}
	return err, result
}

/**
*获取整个应用
* @param AppId 应用id
* @return  未找到时返回null
 */
func (service *AdminAppService) SelectByAppIDs(AppIds []int) *[]adminModel.AdminApp {
	if AppIds == nil {
		return nil
	}
	cacheKeyList := make([]string, 0)
	notExisitIDs := make([]int, 0)
	var err error

	result := make([]adminModel.AdminApp, 0)
	AppIds = joyarray.RemoveDuplicateInt(AppIds)
	if AppIds != nil {
		for _, appid := range AppIds {
			cacheKeyList = append(cacheKeyList, service.getAppIDCacheKey(appid))
		}
		if len(cacheKeyList) > 0 {
			// var cachedModels []*adminModel.AdminUser
			// err =  userCacheObj.Get(cacheKeyList,cachedModels);
			var cachedModel *adminModel.AdminApp
			for _, key := range cacheKeyList {
				err = userCacheObj.Get(key, &cachedModel)
				if err == nil {
					result = append(result, *cachedModel)
				}
			}
		}
		for _, appid := range AppIds {
			exisit := false
			for _, app := range result {
				if appid == app.PId {
					exisit = true
					break
				}
			}
			if !exisit {
				notExisitIDs = append(notExisitIDs, appid)
			}
		}

		if notExisitIDs != nil && len(notExisitIDs) > 0 {
			var appObjs []adminModel.AdminApp
			err := defaultOrm.DB.Model(&adminModel.AdminApp{}).Find(&appObjs, notExisitIDs).Error

			if err == nil {
				for _, appObj := range appObjs {
					cacheKey := service.getAppIDCacheKey((&appObj).PId)
					userCacheObj.Put(cacheKey, &appObj, 1000*60*60*24)
					result = append(result, appObj)

				}

			}
		}
	}
	return &result
}

/**
*查询应用
* @param pAppid 应用id
* @param offset 偏移量
* @param limit 查询结果条数
* @return  未找到时返回null
 */
func (service *AdminAppService) SelectByPage(state int, pageIndex int, pageSize int) (err error, list interface{}, total int64) {
	var result []adminModel.AdminApp
	db := defaultOrm.DB
	if state != -1 {
		db = db.Where("f_state = ?", state)
	}
	err = db.Model(&adminModel.AdminApp{}).Count(&total).Error
	if err == nil {
		err = db.Order("f_id desc").Limit(pageSize).Offset((pageIndex - 1) * pageSize).Find(&result).Error
	}
	return err, result, total
}

/**
*修改应用
* @param record 应用实例
* @return 结果 1:成功 小于1:失败
 */
func (service *AdminAppService) UpdateByPrimaryKey(record *adminModel.AdminApp) int64 {
	result := defaultOrm.DB.Model(&record).Select("f_state", "f_desc", "f_icon").Updates(record)
	if result.Error != nil {
		gologs.GetLogger("orm").Error(result.Error.Error())
		return 0
	}
	if result.RowsAffected > 0 {

	}
	return result.RowsAffected
}

/**
*删除应用
* @param AppID 应用id
* @return 结果 1:成功 小于1:失败
 */
func (service *AdminAppService) DeleteByID(AppID int) int64 {
	err, appObj := service.SelectAppById(AppID)
	if err == nil {
		result := defaultOrm.DB.Where("f_id = ?", AppID).Delete(&adminModel.AdminApp{})
		if result.RowsAffected > 0 {
			service.removeIDAppCache(appObj.PId)
			service.removeNameAppCache(appObj.PName)
		}
		return result.RowsAffected
	} else {
		return -1
	}

}
